from datetime import datetime
import json
import polars as pl
from fastapi import Depends, APIRouter
from pydantic import BaseModel
from util.JWT import get_current_user
from api import sqlpyodbc,sql_polars

sign = APIRouter()

class refreshType(BaseModel):
    cid: str=""
    con: str=""
# 刷新
@sign.post("/refresh")
async def refresh(data: refreshType,id: dict = Depends(get_current_user)):
    sql=''
    if data.cid=='':
        sql=f"""
        select ContractNO,Con_PickingID,Classify,Warehouse,Position,LotNoDate,LotNo from Con_Picking 
        WHERE ContractNO like '%{data.con}%' AND PackageQtyStatus=5 AND DATEDIFF(YEAR,PrintSignTime,'1900-01-01')=0
        """
    else:
        sql=f"""
        select ContractNO,Con_PickingID,Classify,Warehouse,Position,LotNoDate,LotNo from Con_Picking 
        WHERE Con_PickingID='{data.cid}' AND DATEDIFF(YEAR,'1900-01-01',PrintSignTime)>0
        """
    df = sql_polars.query(sql)
    if df.height<1:
        return {
            "code": 204,
            "status": "no",
            "msg": "没有内容",
            "data": []
        }
    df=df.to_dicts()
    json_string = json.dumps(df, ensure_ascii=False)
    return {
        "code": 200,
        "status": "ok",
        "msg": "success",
        "data": json_string
    }


class getdataType(BaseModel):
    flag: bool=False
    cid: str=""
@sign.post("/getprintdata")
async def getprintdata(data:getdataType,id: dict = Depends(get_current_user)):
    sql=''
    if data.flag: #如果勾选了自制件,就全部查询
        sql = f"""
                SELECT a.Item,a.Qty,b.Brand,b.Model,b.Origin,a.EU FROM (
                SELECT Item,EU,SUM(Qty) AS QTY FROM PL_Item where Con_PickingID='{data.cid}' GROUP BY Item,EU) 
                AS A LEFT JOIN Item_Brand AS B on a.Item=b.Item
                """
    else: #如果没有勾选自制件,就只查询外购件
        sql = f"""
                SELECT a.Item,a.Qty,b.Brand,b.Model,b.Origin,a.EU FROM (
                SELECT Item,EU,SUM(Qty) AS QTY FROM PL_Item where Con_PickingID='{data.cid}' AND Itype=1 GROUP BY Item,EU)
                AS A LEFT JOIN Item_Brand AS B on a.Item=b.Item
                """
    df = (
        sql_polars.query(sql)
        .sort("Item")
        .with_columns(pl.when(pl.col("EU") == 1).then(pl.lit("欧盟")).otherwise(pl.lit("")).alias("EU"))
        .to_dicts()
    )
    if df==[]:
        return {
            "code": 204,
            "status": "no",
            "msg": "没有内容",
            "data": []
        }
    json_string = json.dumps(df, ensure_ascii=False)
    return {
        "code": 200,
        "status": "ok",
        "msg": "success",
        "data": json_string
    }

class saveprinttimeType(BaseModel):
    cid: str=""
@sign.post("/saveprinttime")
async def saveprinttime(data:getdataType,id: dict = Depends(get_current_user)):
    if data.cid=="":
        return {
            "code": 500,
            "status": "error",
            "msg": "参数错误",
            "data": []
        }
    sql=f"update Con_Picking set PrintSignTime='{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}' where Con_PickingID='{data.cid}'"
    try:
        if sqlpyodbc.execute(sql)>0:
            return {
                "code": 200,
                "status": "ok",
                "msg": "success",
                "data": []
            }
    except:
        return {
            "code": 500,
            "status": "error",
            "msg": "保存失败",
            "data": []
        }